package com.gupaoedu.vip.singleton.register;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

//容器式单例，spring IOC容易也是采用此方法来管理单例，concurrentHashMap在put值时是线程安全的，但是我们方法本身不安全，
//方便类的管理
//所以通过加锁来保证线程安全
public class ContainerSingleton {

    private static ConcurrentMap<String,Object> ioc = new ConcurrentHashMap<String, Object>();

    private ContainerSingleton (){}

    public static Object getInstance(String name){
        synchronized (ioc) {
            if (!ioc.containsKey(name)) {
                try {
                    Object obj = Class.forName(name).newInstance();
                    ioc.put(name, obj);
                    return obj;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return ioc.get(name);
        }
    }
}
